package com.byox.drawviewproject.slice;

import com.byox.drawviewproject.ResourceTable;
import com.byox.drawviewproject.moudle.ImageInfo;
import com.byox.drawviewproject.provider.PhotoListProvider;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.ability.DataAbilityHelper;
import ohos.aafwk.ability.DataAbilityRemoteException;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.ListContainer;
import ohos.agp.utils.Color;
import ohos.data.resultset.ResultSet;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class PhotoImageAbilitySlice extends AbilitySlice {
    private ListContainer photoList;
    private ImageLoader imageLoader;
    private DirectionalLayout photoLayout;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_photo_image);
        getWindow().setStatusBarColor(Color.getIntColor(getString(ResourceTable.String_StatusBarColor)));
        initImageLoader();
        initView();
    }

    private void initImageLoader() {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(this);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs();
        ImageLoader.getInstance().init(config.build());
    }

    private void initView() {
        photoLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_photoLayout);
        imageLoader = ImageLoader.getInstance();
        photoList = (ListContainer) findComponentById(ResourceTable.Id_photolist);
        List<List<ImageInfo>> provierData = getProvierData();
        if (provierData.size() == 0) {
            photoLayout.setVisibility(Component.VISIBLE);
            return;
        }
        photoLayout.setVisibility(Component.HIDE);
        photoList.setItemProvider(new PhotoListProvider(this, provierData));
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private List<ImageInfo> dispalypic(){
        List<ImageInfo> imgPixelMaps = new ArrayList<>();
        imgPixelMaps.clear();
        try {
            DataAbilityHelper helper = DataAbilityHelper.creator(getContext());
            ResultSet result = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null);
            while (result != null && result.goToNextRow()){
                //获取图片的id
                int imgId = result.getInt(result.getColumnIndexForName(AVStorage.Images.Media.ID));
                //用id转换成uri
                Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, imgId + "");
                InputStream inputStream = DataAbilityHelper.creator(getContext()).obtainInputStream(uri);
                if (inputStream != null) {
                    PixelMap bmp = imageLoader.loadImageSync(uri.toString());
                    ImageInfo imageInfo = new ImageInfo();
                    imageInfo.setPixelMap(bmp);
                    imageInfo.setUri(uri);
                    imgPixelMaps.add(imageInfo);
                }
            }
        } catch (DataAbilityRemoteException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return imgPixelMaps;
    }

    private List<List<ImageInfo>> getProvierData() {
        List<List<ImageInfo>> datas = new ArrayList<>();
        List<ImageInfo> dispalypic = dispalypic();
        System.out.println("dispalypic============" + dispalypic.size());
        int size = dispalypic.size();
        if (size % 3 == 0) {
            for (int row=0; row<size / 3; row++) {
                datas.add(dispalypic.subList(row * 3, (row * 3 + 3)));
            }
        }else {
            if (size % 3 == 1) {
                for (int row=0; row< size/3; row++) {
                    datas.add(dispalypic.subList(row * 3, (row * 3 + 3)));
                }
                List<ImageInfo> pixelMaps = new ArrayList<>();
                pixelMaps.add(dispalypic.get(dispalypic.size()-1));
                datas.add(pixelMaps);
            }if (size % 3 == 2){
                for (int row=0; row< size/3; row++) {
                    datas.add(dispalypic.subList(row * 3, (row * 3 + 3)));
                }
                List<ImageInfo> pixelMaps = new ArrayList<>();
                pixelMaps.add(dispalypic.get(dispalypic.size()-2));
                pixelMaps.add(dispalypic.get(dispalypic.size()-1));
                datas.add(pixelMaps);
            }
        }
        System.out.println("dispalypic============1===" + datas.size());
        return datas;
    }
}
